import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login', '/auth-redirect'] // no redirect whitelist

/**
 * 路由前置守卫
 * @param {Route} to 目标路由
 * @param {Route} from 来源路由
 * @returns
 */
router.beforeEach(async(to, from, next) => {
  //进度条开始
  NProgress.start()
  //设置标题
  document.title = getPageTitle(to.meta.title)
  //确保用户已经登录(获取Token)
  const hasToken = getToken()
  if (hasToken) {
    if (to.path === '/login') {
      //如果已经登录，则重新定向到主页
      next({ path: '/' })
      NProgress.done()
    } else {
      //确保用户是否已通过getUserInfo获取了用户类型
      const hasUserTypeCodes = store.getters.userTypeCodes && store.getters.userTypeCodes.length > 0
      if (hasUserTypeCodes) {
        next()
      } else {
        try {
          //尝试获取用户类型
          const { userTypeCodes } = await store.dispatch('user/getUserInfo')

          //基于用户类型生成可访问路由
          const accessRoutes = await store.dispatch('permission/generateRoutes', userTypeCodes)

          //动态添加可访问路由
          router.addRoutes(accessRoutes)

          // hack method to ensure that addRoutes is complete
          // set the replace: true, so the navigation will not leave a history record
          next({ ...to, replace: true })
        } catch (error) {
          //重设Token并且去登录页重新登录
          await store.dispatch('user/resetToken')
          Message.error(error || 'Has Error')
          next(`/login?redirect=${to.path}`)
          NProgress.done()
        }
      }
    }
  } else {
    //没有Token
    if (whiteList.indexOf(to.path) !== -1) {
      //在免登录白名单
      next()
    } else {
      //没有访问权限这重定向到登录页
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  //进度条完成
  NProgress.done()
})
